package com.example.jin.myapplication;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;

import java.util.List;
import java.util.UUID;


/**
 * Created by jin on 2016/5/30.
 */
public class CrimeListFragment extends Fragment{
    private RecyclerView mRecyclerView;
    private CrimeAdapter mAdapter;
    private boolean mbShowTitle=false;
    private List<Crime> mCrimes;
    private Callback mCallback;
    private void updateSubTitle(){
        String title=null;
        if(mbShowTitle) {
            int size = CrimeList.Instance(getActivity()).getCrimes().size();
            title=getString(R.string.subtitle_format, size);
        }
        ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(title);
    }
    public interface Callback{
        void onItemClicked(Crime crime);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==0){
            Log.i("main","onActivityResult:"+resultCode);
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu,inflater);
        inflater.inflate(R.menu.crime_action_menu,menu);  //menu中使用的icon是从Android的image asset中导出的
        MenuItem menuItem=menu.findItem(R.id.action_show_title);
        if(mbShowTitle==true)
            menuItem.setTitle("Hide Sub Title");
        else
            menuItem.setTitle("Show Sub Title");
    }

    //菜单处理
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case R.id.action_add_crime:
                Snackbar.make(getView(),"Add",Snackbar.LENGTH_LONG).show();
                Crime crime=new Crime(UUID.randomUUID());
                CrimeList.Instance(getActivity()).addCrime(crime);
                updateUI();
                if(mCallback!=null)
                {
                    mCallback.onItemClicked(crime);
                }
                return true;
            case R.id.action_show_title:
                mbShowTitle=!mbShowTitle;
                updateSubTitle();
                //重新建立Menu
                ((AppCompatActivity)getActivity()).invalidateOptionsMenu();
                return true;
            case R.id.action_reflect: {
                //Context.getSystemService(Context.ETHERNET_SERVICE);
                return true;
            }
        }
        return super.onOptionsItemSelected(item);
    }

    //设备配置发生改变时调用(屏幕旋转或者语言变化)
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean("subtitle",mbShowTitle);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.i("main","onCreateView");

        View view=inflater.inflate(R.layout.fragment_crimelist,container,false);
        mRecyclerView=(RecyclerView)view.findViewById(R.id.recyclerview);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        mAdapter=new CrimeAdapter();
        mRecyclerView.setAdapter(mAdapter);
        return view;
    }
    //Activity在此绑定了Fragment，可以使用context作为Activity
    //这里默认Activity实现了Callback函数，需要特别注明
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mCallback=(Callback) context;
        Log.i("main","onAttach");
    }
    //解除绑定
    @Override
    public void onDetach() {
        super.onDetach();
        mCallback=null;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i("main","onCreate");
        //明确告诉FragmentManager有菜单, Fragment有Toolbar才行
        //Toolbar可以当做一个View来使用，且风格和ActionBar不一样
        setHasOptionsMenu(true);
        if(savedInstanceState!=null)
            mbShowTitle=savedInstanceState.getBoolean("subtitle");
        else
            mbShowTitle=getActivity().getIntent().getBooleanExtra("subtitle",false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.i("main","onActivityCreated");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.i("main","onResume");
        updateUI();
    }
    //Activity也可以调用这个接口
    public void updateUI()
    {
        if(mAdapter==null){
            mAdapter=new CrimeAdapter();
        }
        else{
            mAdapter.updateList();
            mAdapter.notifyDataSetChanged();
        }
        updateSubTitle();
    }
    //定义Adapter
    private class CrimeAdapter extends RecyclerView.Adapter<CrimeViewHolder>{
        public CrimeAdapter(){
            updateList();
        }
        public void updateList(){
            mCrimes=CrimeList.Instance(getActivity()).getCrimes();
        }
        @Override
        public CrimeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            //onCreateViewHolder只会调用有限次数
            View view=LayoutInflater.from(getActivity()).inflate(R.layout.item_crime,parent,false);
            return new CrimeViewHolder(view);
        }

        @Override
        public void onBindViewHolder(CrimeViewHolder holder, int position) {
            //可能调用很多次
            holder.bindView(mCrimes.get(position));
        }

        @Override
        public int getItemCount() {
            return mCrimes.size();
        }
    }
    //定义ViewHolder
    private class CrimeViewHolder extends RecyclerView.ViewHolder{
        TextView title;
        TextView date;
        CheckBox solved;
        Crime mCrime=null;
        public CrimeViewHolder(View itemView) {
            super(itemView);
            title=(TextView)itemView.findViewById(R.id.crime_title);
            date=(TextView)itemView.findViewById(R.id.crime_date);
            solved=(CheckBox)itemView.findViewById(R.id.crime_solved);

            //点击事件处理
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.i("main","onClicked");
                    Snackbar.make(v,mCrime.getTitle(),Snackbar.LENGTH_LONG).show();
                    if(null!=mCallback)
                    {
                        mCallback.onItemClicked(mCrime);
                    }
                    updateUI();
                }
            });
        }
        public  void bindView(Crime crime){
            mCrime=crime;
            title.setText(crime.getTitle());
            date.setText(crime.getDate().toString());
            solved.setChecked(crime.isSolved());
        }
    }


}
